package cn.tianyigps.tianyigpsgatherchecker.handler;

import cn.tianyigps.tianyigpsgatherchecker.constant.UrlConstant;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.StringWriter;

/**
 * Created with IntelliJ IDEA
 * Created By yangxl
 * Date: 2018/6/13
 * Time: 18:11
 * Description:推送报警数据到Php
 */
@Slf4j
public class PushAlarmData {
    private RestTemplate restTemplate = new RestTemplate();
    private ObjectMapper mapper;

    public boolean pushAlarmDataByPost(Object object) {
        mapper = new ObjectMapper();
        StringWriter writer = new StringWriter();
//        String alarmStr = gson.toJson(object);
//        Map  map = gson.fromJson(alarmStr,Map.class);
//        map.remove("id");
//        map.remove("duration");
        //  一定要设置header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //  将提交的数据转换为String
        //  最好通过bean注入的方式获取ObjectMapper
        HttpEntity<Object> requestEntity = new HttpEntity<>(object, headers);
        log.info(requestEntity.toString());
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(UrlConstant.ALARM_URL, requestEntity, String.class);
        String jsonStr = responseEntity.getBody();
        log.info(jsonStr);

        try {
            JsonGenerator gen = new JsonFactory().createGenerator(writer);
            mapper.writeValue(gen, object);
            gen.close();
            String json = writer.toString();
            JsonNode node = mapper.readTree(jsonStr);
            boolean success = node.get("success").asBoolean();
            if (success) {
                log.info("报警数据推送成功" + json);

            } else {
                log.error("报警数据推送失败: " + json);
                log.error("报警数据推送json: " + jsonStr);
                return false;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;


    }
}